package cn.yllr.tomgxianghui.controller;

import cn.yllr.tomgxianghui.entity.Admin;
import cn.yllr.tomgxianghui.entity.User;
import cn.yllr.tomgxianghui.service.AdminService;
import cn.yllr.tomgxianghui.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.regex.Pattern;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2021-12-21 00:07:47
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Admin selectOne(String id) {
        return this.adminService.queryById(id);
    }

    @RequestMapping("/login")
    public String admin_login(){
        return "admin/admin_login";
    }

    /**
     * 管理员登录
     *
     * @param account
     * @param password
     * @param checkCode
     * @param session
     * @param redirect
     * @return
     */
    @PostMapping("/login.do")
    public String login(@RequestParam("username") String account, String password, String checkCode,
                        HttpSession session, RedirectAttributes redirect) {
        //使用卫语句，减少else出现，做排除法，不满足直接跳出，不做过多判断
        if (account != null && password != null && checkCode != null) {
            if (!checkCode.equalsIgnoreCase(session.getAttribute("randomcode_key").toString())) {
                redirect.addFlashAttribute("result", "验证码错误请重新输入");
                return "redirect:login";
            }
            Admin admin;
            /*邮箱正则*/
            String email_reg = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
            if (Pattern.matches(email_reg, account)) {
                admin=this.adminService.queryByEmail(account);
            }else {
                admin = this.adminService.queryById(account);
            }

            if (admin == null) {
                redirect.addFlashAttribute("result", "账号不存在");
                return "redirect:login";
            }
            if (!MD5Util.EncodeByMD5(password).equals(admin.getPassword())) {
                redirect.addFlashAttribute("result", "密码错误，请重新输入");
                return "redirect:login";
            }
        }
        return "redirect:index";
    }

    @RequestMapping("/index")
    public String admin_index(){
        return "admin/index-manage";
    }


}